package com.jy.admin.rest;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fqgj.common.api.Page;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.DateUtil;
import com.fqgj.common.utils.StringUtils;
import com.fqgj.exception.common.ApplicationException;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jsoniter.JsonIterator;
import com.jsoniter.output.JsonStream;
import com.jy.admin.annotations.AdminSignIgnore;
import com.jy.admin.auth.anno.VisitorAccessible;
import com.jy.admin.auth.request.AccountAddRequest;
import com.jy.admin.auth.request.AccountRequest;
import com.jy.admin.db.dao.CeOrdersDao;
import com.jy.admin.db.entity.*;
import com.jy.admin.enums.WhiteListBean;
import com.jy.admin.services.cashPocket.OkRupeeService;
import com.jy.admin.services.cashPocket.vo.FailLoginRequest;
import com.jy.admin.auth.request.AccountUpdateRequest;
import com.jy.admin.auth.request.MerchantAddRequest;
import com.jy.admin.auth.response.AccountListResponse;
import com.jy.admin.auth.response.AccountsResponse;
import com.jy.admin.auth.response.MerchantListResponse;
import com.jy.admin.auth.vo.AccountInfoVo;
import com.jy.admin.auth.vo.AccountVo;
import com.jy.admin.db.dao.CeAgentAccountDao;
import com.jy.admin.db.dao.CeMerchantDao;
import com.jy.admin.services.cashPocket.vo.FailAccountListResponse;
import com.jy.bo.common.conf.api.ApiResponse;
import com.jy.bo.common.conf.enums.AccountGetUrlEnum;
import com.jy.bo.common.conf.util.HttpUtil;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;


@RestController
@RequestMapping("/account")
public class AccountController {
    private final static Logger LOGGER = LoggerFactory.getLogger(AccountController.class);

    @Autowired
    CeAgentAccountDao ceAgentAccountDao;

    @Autowired
    CeMerchantDao ceMerchantDao;

    @Autowired
    CeOrdersDao ordersDao;


    @Autowired
    OkRupeeService okRupeeService;

    @AdminSignIgnore
    @RequestMapping("/list")
    public ApiResponse<AccountsResponse> queryAccount() {
        List<CeAgentAccountEntity> ceAgentAccountEntities = ceAgentAccountDao.queryAll();
        List<AccountInfoVo> newArrayList = Lists.newArrayList();
        ceAgentAccountEntities.forEach(ceAgentAccountEntity -> {
            CeMerchantEntity ceMerchantEntity = ceMerchantDao.queryMerchantByCode(ceAgentAccountEntity.getMerchantCode());
            if (ceMerchantEntity != null) {
                newArrayList.add(new AccountInfoVo(ceAgentAccountEntity.getAgentCode(), ceAgentAccountEntity.getAccount(), ceAgentAccountEntity.getPassword(), ceMerchantEntity.getSystemUrl(), ceAgentAccountEntity.getLoginStatus(), false, ceMerchantEntity.getMerchantCode()));
            }
        });
        AccountsResponse response = new AccountsResponse();
        response.setList(newArrayList);
        return new ApiResponse<>(response);
    }

    @RequestMapping("/needlist")
    public ApiResponse<FailAccountListResponse> queryNeedAccount(@RequestBody FailLoginRequest request) {
        LOGGER.info("=== 选择商户 ==,request:{}", JsonStream.serialize(request));
        List<CeAgentAccountEntity> ceAgentAccountEntities = ceAgentAccountDao.selectNoLoginList(request.getMerchantCode());
        if (CollectionUtils.isEmpty(ceAgentAccountEntities)) {
            LOGGER.info("== not login list ==");
            return new ApiResponse<>();
        }
        return new ApiResponse<>(new FailAccountListResponse(ceAgentAccountEntities));
    }

    @AdminSignIgnore
    @RequestMapping("/token/add")
    public ApiResponse addToken(@RequestBody AccountRequest request) {
        CeAgentAccountEntity queryAccount = ceAgentAccountDao.queryAccount(request.getAccount(), request.getMerchantCode());
        if (queryAccount != null) {
            JSONObject jsonObject = new JSONObject();
            if (request.getMerchantCode().equals("cashpocket") || request.getMerchantCode().equals("plumpwallet") || request.getMerchantCode().equals("peonycashtreeloan") || request.getMerchantCode().equals("loannow")) {
                jsonObject.put("X-ADMIN-TOKEN", request.getToken());
            } else if (request.getMerchantCode().equals("income")) {
                jsonObject.put("token", request.getToken());
                jsonObject.put("tm", request.getTm());
            } else if (request.getMerchantCode().equals("cashfish") || request.getMerchantCode().equals("credexpress")) {
                jsonObject.put("Authorization", request.getToken());
            } else if (request.getMerchantCode().equals("cbcash") || request.getMerchantCode().equals("okloan") || request.getMerchantCode().equals("lendking") || request.getMerchantCode().equals("richcash")) {
                jsonObject.put("cookie", request.getToken());
            } else if (request.getMerchantCode().equals("rupeego") || request.getMerchantCode().equals("therupee")) {
                jsonObject.put("accessToken", request.getToken());
                jsonObject.put("appCode", "1");
                jsonObject.put("basicParams", "{'appClient': 'web'}");
                jsonObject.put("Content-Type", "application/json");
            }
            queryAccount.setRequestHeader(jsonObject.toString());
            String url = "";
            if (request.getMerchantCode().equals("cashpocket")) {
                url = AccountGetUrlEnum.CASHPOCKETURL.getUrl();
            } else if (request.getMerchantCode().equals("plumpwallet")) {
                url = AccountGetUrlEnum.PLUMPWALLET.getUrl();
            } else if (request.getMerchantCode().equals("peonycashtreeloan")) {
                url = AccountGetUrlEnum.TREELOAN.getUrl();
            } else if (request.getMerchantCode().equals("loannow")) {
                url = AccountGetUrlEnum.LOANNOW.getUrl();
            } else if (request.getMerchantCode().equals("income")) {
                url = AccountGetUrlEnum.INCOMEURL.getUrl();
            } else if (request.getMerchantCode().equals("cashfish")) {
                url = AccountGetUrlEnum.CASHFISH.getUrl();
            } else if (request.getMerchantCode().equals("credexpress")) {
                url = AccountGetUrlEnum.CREDEXPRESS.getUrl();
            } else if (request.getMerchantCode().equals("cbcash")) {
                url = AccountGetUrlEnum.CBCASH.getUrl();
            } else if (request.getMerchantCode().equals("okloan")) {
                url = AccountGetUrlEnum.OKLOAN.getUrl();
            } else if (request.getMerchantCode().equals("lendking")) {
                url = AccountGetUrlEnum.LENDkING.getUrl();
            } else if (request.getMerchantCode().equals("rupeego") || request.getMerchantCode().equals("therupee")) {
                url = AccountGetUrlEnum.RUPEEGO.getUrl();
            } else if (request.getMerchantCode().equals("richcash")) {
                url = AccountGetUrlEnum.RICHCASH.getUrl();
            }
            Map<String, String> map = jsonObject.toJavaObject(Map.class);
            String page;
            if (request.getMerchantCode().equals("credexpress")) {
                page = HttpUtil.postPage(url, null, map);
                queryAccount.setLoginStatus(!page.equals("") ? 1 : 2);
            } else if (request.getMerchantCode().equals("cashpocket") || request.getMerchantCode().equals("plumpwallet") || request.getMerchantCode().equals("peonycashtreeloan") || request.getMerchantCode().equals("loannow")) {
                page = HttpUtil.getPage(url, null, map);
                queryAccount.setLoginStatus(!page.equals("") ? 1 : 2);
            } else if (request.getMerchantCode().equals("income")) {
                page = HttpUtil.getPage(url, null, map);
                JSONObject result = JSONObject.parseObject(page);
                JSONArray data = result.getJSONArray("data");
                queryAccount.setLoginStatus(data.size() > 0 ? 1 : 2);
            } else if (request.getMerchantCode().equals("cbcash") || request.getMerchantCode().equals("okloan") || request.getMerchantCode().equals("lendking")) {
                page = HttpUtil.getPage(url, null, map);
                if (page.contains("ID") && page.contains("order-id") && page.contains("user-name") && page.contains("user-phone no.") && page.contains("UserLevel")) {
                    queryAccount.setLoginStatus(1);
                } else {
                    queryAccount.setLoginStatus(2);
                }
            } else if (request.getMerchantCode().equals("richcash")) {
                page = HttpUtil.getPage(url, null, map);
                if (page.contains("Market Flag") && page.contains("ID") && page.contains("order number") && page.contains("name") && page.contains("phone number")) {
                    queryAccount.setLoginStatus(1);
                } else {
                    queryAccount.setLoginStatus(2);
                }
            } else if (request.getMerchantCode().equals("rupeego") || request.getMerchantCode().equals("therupee")) {
                page = HttpUtil.postPage(url, null, map);
                JSONObject result = JSONObject.parseObject(page);
                JSONObject data = result.getJSONObject("data");
                queryAccount.setLoginStatus(data != null ? 1 : 2);
            } else {
                page = HttpUtil.getPage(url, null, map);
                JSONObject result = JSONObject.parseObject(page);
                JSONObject data = result.getJSONObject("data");
                queryAccount.setLoginStatus(data.size() > 0 ? 1 : 2);
            }
            queryAccount.setLoginDt(new Date());
            ceAgentAccountDao.updateByPrimaryKey(queryAccount);
        }
        return new ApiResponse("Success");
    }

    @AdminSignIgnore
    @RequestMapping("/init")
    public ApiResponse init() {
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(10); // 10 为线程数量  // 执行任务
        scheduledExecutorService.scheduleAtFixedRate(() -> {
            getHttp();
        }, 0, 30, TimeUnit.SECONDS); // 10s 后开始执行，每 10s 执行一次
        return new ApiResponse("Success");
    }

    public void getHttp() {
        List<CeAgentAccountEntity> ceAgentAccountEntities = ceAgentAccountDao.queryAll();
        ceAgentAccountEntities.forEach(ceAgentAccountEntity -> {
            if (ceAgentAccountEntity.getRequestHeader() != null) {
                JSONObject jsonObject = JSONObject.parseObject(ceAgentAccountEntity.getRequestHeader());
                String url = "";
                if (ceAgentAccountEntity.getMerchantCode().equals("cashpocket")) {
                    url = AccountGetUrlEnum.CASHPOCKETURL.getUrl();
                } else if (ceAgentAccountEntity.getMerchantCode().equals("plumpwallet")) {
                    url = AccountGetUrlEnum.PLUMPWALLET.getUrl();
                } else if (ceAgentAccountEntity.getMerchantCode().equals("peonycashtreeloan")) {
                    url = AccountGetUrlEnum.TREELOAN.getUrl();
                } else if (ceAgentAccountEntity.getMerchantCode().equals("loannow")) {
                    url = AccountGetUrlEnum.LOANNOW.getUrl();
                } else if (ceAgentAccountEntity.getMerchantCode().equals("income")) {
                    url = AccountGetUrlEnum.INCOMEURL.getUrl();
                } else if (ceAgentAccountEntity.getMerchantCode().equals("cashfish")) {
                    url = AccountGetUrlEnum.CASHFISH.getUrl();
                } else if (ceAgentAccountEntity.getMerchantCode().equals("credexpress")) {
                    url = AccountGetUrlEnum.CREDEXPRESS.getUrl();
                } else if (ceAgentAccountEntity.getMerchantCode().equals("cbcash")) {
                    url = AccountGetUrlEnum.CBCASH.getUrl();
                } else if (ceAgentAccountEntity.getMerchantCode().equals("okloan")) {
                    url = AccountGetUrlEnum.OKLOAN.getUrl();
                } else if (ceAgentAccountEntity.getMerchantCode().equals("lendking")) {
                    url = AccountGetUrlEnum.LENDkING.getUrl();
                } else if (ceAgentAccountEntity.getMerchantCode().equals("rupeego") || ceAgentAccountEntity.getMerchantCode().equals("therupee")) {
                    url = AccountGetUrlEnum.RUPEEGO.getUrl();
                } else if (ceAgentAccountEntity.getMerchantCode().equals("richcash")) {
                    url = AccountGetUrlEnum.RICHCASH.getUrl();
                }
                Map<String, String> map = jsonObject.toJavaObject(Map.class);
                String page;
                if (ceAgentAccountEntity.getMerchantCode().equals("credexpress")) {
                    page = HttpUtil.postPage(url, null, map);
                    ceAgentAccountEntity.setLoginStatus(!page.equals("") ? 1 : 2);
                } else if (ceAgentAccountEntity.getMerchantCode().equals("cashpocket") || ceAgentAccountEntity.getMerchantCode().equals("plumpwallet") || ceAgentAccountEntity.getMerchantCode().equals("peonycashtreeloan") || ceAgentAccountEntity.getMerchantCode().equals("loannow")) {
                    page = HttpUtil.postPage(url, null, map);
                    ceAgentAccountEntity.setLoginStatus(!page.equals("") ? 1 : 2);
                } else if (ceAgentAccountEntity.getMerchantCode().equals("income")) {
                    page = HttpUtil.getPage(url, null, map);
                    JSONObject result = JSONObject.parseObject(page);
                    JSONArray data = result.getJSONArray("data");
                    ceAgentAccountEntity.setLoginStatus(data.size() > 0 ? 1 : 2);
                } else if (ceAgentAccountEntity.getMerchantCode().equals("cbcash") || ceAgentAccountEntity.getMerchantCode().equals("okloan") || ceAgentAccountEntity.getMerchantCode().equals("lendking")) {
                    page = HttpUtil.getPage(url, null, map);
                    if (page.contains("ID") && page.contains("order-id") && page.contains("user-name：") && page.contains("user-phone no.") && page.contains("UserLevel")) {
                        ceAgentAccountEntity.setLoginStatus(1);
                    } else {
                        ceAgentAccountEntity.setLoginStatus(2);
                    }
                } else if (ceAgentAccountEntity.getMerchantCode().equals("richcash")) {
                    page = HttpUtil.getPage(url, null, map);
                    if (page.contains("Market Flag") && page.contains("ID") && page.contains("order number") && page.contains("name") && page.contains("phone number")) {
                        ceAgentAccountEntity.setLoginStatus(1);
                    } else {
                        ceAgentAccountEntity.setLoginStatus(2);
                    }
                } else if (ceAgentAccountEntity.getMerchantCode().equals("rupeego") || ceAgentAccountEntity.getMerchantCode().equals("therupee")) {
                    page = HttpUtil.postPage(url, null, map);
                    JSONObject result = JSONObject.parseObject(page);
                    JSONObject data = result.getJSONObject("data");
                    ceAgentAccountEntity.setLoginStatus(data != null ? 1 : 2);
                } else {
                    page = HttpUtil.getPage(url, null, map);
                    JSONObject result = JSONObject.parseObject(page);
                    JSONObject data = result.getJSONObject("data");
                    ceAgentAccountEntity.setLoginStatus(data.size() > 0 ? 1 : 2);
                }
            }
        });
    }


    @AdminSignIgnore
    @RequestMapping("/account/list")
    public ApiResponse<AccountListResponse> getAccountList(int currentPage, String merchantCode) {
        Page page = new Page();
        page.setCurrentPage(currentPage);
        page.setPageSize(20);
        ArrayList<AccountVo> newArrayList = Lists.newArrayList();
        List<CeAgentAccountEntity> ceAgentAccountEntities;
        if (StringUtils.isEmpty(merchantCode)) {
            ceAgentAccountEntities = ceAgentAccountDao.queryAccountAll(page);
            page.setTotalCount(ceAgentAccountDao.selectAllCount());
        } else {
            ceAgentAccountEntities = ceAgentAccountDao.queryAccountByMerchant(page, merchantCode);
            page.setTotalCount(ceAgentAccountDao.selectCountByMerchant(merchantCode));
        }
        for (int i = 0; i < ceAgentAccountEntities.size(); i++) {
            newArrayList.add(new AccountVo(ceAgentAccountEntities.get(i).getAgentCode(),
                    ceAgentAccountEntities.get(i).getAccount(), ceAgentAccountEntities.get(i).getPassword(),
                    ceAgentAccountEntities.get(i).getLoginStatus(), ceAgentAccountEntities.get(i).getAppName(),
                    ceAgentAccountEntities.get(i).getMerchantCode(), ceAgentAccountEntities.get(i).getRefreshToday(),
                    ceAgentAccountEntities.get(i).getLoginDt() != null ? DateFormatUtils.format(ceAgentAccountEntities.get(i).getLoginDt(), "yyyy-MM-dd") : "", ceAgentAccountEntities.get(i).getRequestHeader(), ceAgentAccountEntities.get(i).getOrderCnt()));
        }
        AccountListResponse response = new AccountListResponse();
        response.setList(newArrayList);
        return new ApiResponse<>(response).setPage(page);
    }


    @AdminSignIgnore
    @RequestMapping("/merchant/list")
    public ApiResponse<MerchantListResponse> getMerchantList() {
        List<CeMerchantEntity> allActiveMerchant = ceMerchantDao.getAllActiveMerchant();
        MerchantListResponse response = new MerchantListResponse();
        response.setList(allActiveMerchant);
        return new ApiResponse<>(response);
    }

    @AdminSignIgnore
    @RequestMapping("/account/query")
    public ApiResponse<AccountListResponse> getMerchantCodeQuery(int currentPage, String code) {
        Page page = new Page();
        page.setCurrentPage(currentPage);
        page.setPageSize(20);
        List<CeAgentAccountEntity> ceAgentAccountEntities = ceAgentAccountDao.queryAccountByMerchant(page, code);
        ArrayList<AccountVo> newArrayList = Lists.newArrayList();
        for (int i = 0; i < ceAgentAccountEntities.size(); i++) {
            newArrayList.add(new AccountVo(ceAgentAccountEntities.get(i).getAgentCode(),
                    ceAgentAccountEntities.get(i).getAccount(), ceAgentAccountEntities.get(i).getPassword(),
                    ceAgentAccountEntities.get(i).getLoginStatus(), ceAgentAccountEntities.get(i).getAppName(),
                    ceAgentAccountEntities.get(i).getMerchantCode(), ceAgentAccountEntities.get(i).getRefreshToday(),
                    DateFormatUtils.format(ceAgentAccountEntities.get(i).getLoginDt(), "yyyy-MM-dd"), ceAgentAccountEntities.get(i).getRequestHeader(), ceAgentAccountEntities.get(i).getOrderCnt()));
        }
        AccountListResponse response = new AccountListResponse();
        response.setList(newArrayList);
        page.setTotalCount(ceAgentAccountDao.selectCountByMerchant(code));
        return new ApiResponse<>(response).setPage(page);
    }

    @AdminSignIgnore
    @RequestMapping("/account/del")
    public ApiResponse getMerchantCodeQuery(String account, String code) {
        CeAgentAccountEntity queryAccount = ceAgentAccountDao.queryAccount(account, code);
        if (queryAccount != null) {
            queryAccount.setDeleted(true);
            ceAgentAccountDao.updateByPrimaryKey(queryAccount);
        }
        return new ApiResponse("Success");
    }

    @AdminSignIgnore
    @RequestMapping("/account/add")
    public ApiResponse getAccountAdd(@RequestBody AccountAddRequest request) {
        if (StringUtils.isEmpty(request.getAgentCode()) || StringUtils.isEmpty(request.getAccount()) || StringUtils.isEmpty(request.getPassword()) || StringUtils.isEmpty(request.getMerchantCode()) || StringUtils.isEmpty(request.getStage())) {
            throw new ApplicationException("创建账号错误");
        }
        CeAgentAccountEntity ceAgentAccountEntity = ceAgentAccountDao.queryAccount(request.getAccount(), request.getMerchantCode());
        if (ceAgentAccountEntity != null) {
            throw new ApplicationException("账号已存在");
        }
        CeAgentAccountEntity agentAccountEntity = ceAgentAccountDao.getByAgentCode(request.getAgentCode());
        if (agentAccountEntity != null) {
            throw new ApplicationException("坐席名称已存在，请更换");
        }
        CeAgentAccountEntity entity = new CeAgentAccountEntity();
        entity.setMerchantCode(request.getMerchantCode());
        entity.setAgentCode(request.getAgentCode());
        entity.setAccount(request.getAccount());
        entity.setPassword(request.getPassword());
        entity.setStatus(1);
        entity.setLoginStatus(2);
        entity.setAppName(request.getMerchantCode());
        entity.setDeleted(false);
        entity.setStage(request.getStage());
        entity.setLoginDt(new Date());
        JSONObject header = new JSONObject();
        header.put("Content-Type", "application/json");
        entity.setRequestHeader(header.toString());
        ceAgentAccountDao.insert(entity);
        return new ApiResponse("Success");
    }

    @AdminSignIgnore
    @RequestMapping("/account/reduction")
    public ApiResponse getAccountReduction(@RequestBody AccountAddRequest request) {
        if (StringUtils.isEmpty(request.getMerchantCode())) {
            throw new ApplicationException("请选择商户");
        }
        CeAgentAccountEntity ceAgentAccountEntity = ceAgentAccountDao.queryAccount(request.getAccount(), request.getMerchantCode());
        if (ceAgentAccountEntity == null) {
            throw new ApplicationException("账号不存在");
        }
        ceAgentAccountEntity.setDeleted(true);
        ceAgentAccountDao.updateByPrimaryKey(ceAgentAccountEntity);
        return new ApiResponse("Success");
    }

    @AdminSignIgnore
    @RequestMapping("/merchant/add")
    public ApiResponse getMerchantAdd(@RequestBody MerchantAddRequest request) {
        if (StringUtils.isEmpty(request.getHasCapcha()) || StringUtils.isEmpty(request.getSystemUrl()) || StringUtils.isEmpty(request.getApiDomain()) || StringUtils.isEmpty(request.getMerchantCode())) {
            throw new ApplicationException("创建商户错误");
        }
        CeMerchantEntity ceMerchantEntity = ceMerchantDao.queryMerchantByCode(request.getMerchantCode());
        if (ceMerchantEntity != null) {
            throw new ApplicationException("商户已存在");
        }

        CeMerchantEntity entity = new CeMerchantEntity();
        entity.setApiDomain(request.getApiDomain());
        entity.setHasCapcha(Integer.parseInt(request.getHasCapcha()));
        entity.setSystemUrl(request.getSystemUrl());
        entity.setMerchantCode(request.getMerchantCode());
        entity.setName(request.getMerchantCode());
        entity.setDeleted(false);
        ceMerchantDao.insert(entity);
        return new ApiResponse("Success");
    }

    @AdminSignIgnore
    @RequestMapping("/merchant/update")
    public ApiResponse getMerchantUpdate(String merchantCode) {
        CeMerchantEntity ceMerchantEntity = ceMerchantDao.queryMerchantByCode(merchantCode);
        if (ceMerchantEntity == null) {
            throw new ApplicationException("商户不存在");
        }
        ceMerchantEntity.setStatus(1);
        ceMerchantDao.updateByPrimaryKey(ceMerchantEntity);
        return new ApiResponse("Success");
    }


    @AdminSignIgnore
    @RequestMapping("/account/update")
    public ApiResponse getAccountUpdate(@RequestBody AccountUpdateRequest request) {
        if (StringUtils.isEmpty(request.getAgentCode()) || StringUtils.isEmpty(request.getAccount()) || StringUtils.isEmpty(request.getPassword()) || StringUtils.isEmpty(request.getMerchantCode())) {
            throw new ApplicationException("修改失败");
        }
        CeAgentAccountEntity ceAgentAccountEntity = ceAgentAccountDao.queryAccount(request.getAccount(), request.getMerchantCode());
        if (ceAgentAccountEntity == null) {
            throw new ApplicationException("账户不存在");
        }
        ceAgentAccountEntity.setAgentCode(request.getAgentCode());
        ceAgentAccountEntity.setAccount(request.getAccount());
        ceAgentAccountEntity.setPassword(request.getPassword());
        ceAgentAccountEntity.setAppName(request.getAppName());
        ceAgentAccountEntity.setMerchantCode(request.getMerchantCode());
        ceAgentAccountDao.updateByPrimaryKey(ceAgentAccountEntity);
        return new ApiResponse("Success");
    }



    @PostMapping("/upload")
    public ApiResponse uploadFile(@RequestPart("file") MultipartFile files, String merchantCode) {
        if (StringUtils.isEmpty(merchantCode)) {
            return new ApiResponse(400, "商户未选择");
        }
        CeMerchantEntity ceMerchantEntity = ceMerchantDao.queryMerchantByCode(merchantCode);
        if (ceMerchantEntity == null) {
            return new ApiResponse(400, "商户不存在");
        }
        String filename = files.getOriginalFilename();
        long size = files.getSize();
        String prefix = null;
        if (filename != null) {
            prefix = filename.substring(filename.lastIndexOf(".") + 1);
        }
        LOGGER.info("====,filename:{},size:{},prefix:{}", filename, size, prefix);
        try {
            ArrayList<ExcelEntity> allAccount = Lists.newArrayList();
            XSSFWorkbook xssfSheets = new XSSFWorkbook(files.getInputStream());
            XSSFSheet sheet0 = xssfSheets.getSheetAt(0);
            int physicalNumberOfRows = sheet0.getPhysicalNumberOfRows();
            LOGGER.info("===,physicalNumberOfRows:{}", physicalNumberOfRows);
            for (int i = 0; i < physicalNumberOfRows; i++) {
                XSSFRow row = sheet0.getRow(i);
                if (row == null) {
                    break;
                }
                LOGGER.info("====,i:{},row:{}", i, row.getCell(1).getStringCellValue());
                ExcelEntity entity = new ExcelEntity();
                entity.setAccount(row.getCell(1).getStringCellValue());
                entity.setPwd(row.getCell(2).getStringCellValue());
                allAccount.add(entity);
            }
            AtomicInteger modifyNumber = new AtomicInteger();
            allAccount.forEach(excelEntity -> {
                CeAgentAccountEntity agentAccountEntity = ceAgentAccountDao.queryAccount(excelEntity.getAccount(), merchantCode);
                if (agentAccountEntity == null) {
                    LOGGER.info("== 该坐席不存在 ==");
                    return;
                }
                agentAccountEntity.setPassword(excelEntity.getPwd());
                ceAgentAccountDao.updateByPrimaryKey(agentAccountEntity);
                modifyNumber.getAndIncrement();
            });
            return new ApiResponse("成功修改坐席数：" + modifyNumber);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ApiResponse(400, "error");

    }


    @AdminSignIgnore
    @RequestMapping("/white/list")
    public ApiResponse getDownloadWhiteList(HttpServletResponse request) {
        List<WhiteListBean> whiteList = ceAgentAccountDao.getWhiteList("rasiecash", "1");
        List<Integer> repeatWhiteList = ceAgentAccountDao.getRepeatWhiteList();
        String repeatWhiteListString = JsonStream.serialize(repeatWhiteList);
        LOGGER.info("===getDownloadWhiteList===,repeatWhiteListString:{}", repeatWhiteListString);
        StringBuilder params = new StringBuilder();
        for (int i = 0; i < whiteList.size(); i++) {
            boolean contains = repeatWhiteListString.contains(whiteList.get(i).getMobile());
            if (contains) {
                whiteList.remove(i);
            } else {
                params.append(whiteList.get(i).getMobile()).append(",");
            }
        }
        String url = "https://prod.rich-loan.com/api/manage/white/add";
        HashMap<String, String> header = Maps.newHashMap();
        header.put("username", "raise");
        header.put("password", "08a763c89c824b6faada5f538383e001");
        header.put("Content-Type", "text/plain");
        String param = params.substring(0, params.toString().length() - 1);
        LOGGER.info("==getDownloadWhiteList==,param:{}", param);
        String result = HttpUtil.postPageText(url, header, param);
        LOGGER.info("==getDownloadWhiteList==,result:{}", result);
        String blackList = JsonIterator.deserialize(result).get("data").get("blackList").toString();
        LOGGER.info("==getDownloadWhiteList==,blackList:{}", blackList);
        if (CollectionUtils.isNotEmpty(JsonIterator.deserialize(result).get("data").get("blackList").asList())) {
            for (int i = 0; i < whiteList.size(); i++) {
                boolean contains = blackList.contains(whiteList.get(i).getMobile());
                if (contains) {
                    whiteList.remove(i);
                }
            }
        }
        try {
            ServletOutputStream outputStream = request.getOutputStream();
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet1 = workbook.createSheet("sheet1");
            Row row0 = sheet1.createRow(0);
            row0.createCell(0).setCellValue("phone");
            row0.createCell(1).setCellValue("name");
            for (int i = 0; i < whiteList.size(); i++) {
                Row row = sheet1.createRow(i + 1);
                row.createCell(0).setCellValue(whiteList.get(i).getMobile());
                row.createCell(1).setCellValue(whiteList.get(i).getName());
            }
            request.reset();
            request.setHeader("Content-Disposition", "attchement;filename=" + new String((DateUtil.getDate("yyyy-MM-dd") + ".xlsx").getBytes("gb2312"), "ISO8859-1"));
            request.setContentType("application/msexcel");
            workbook.write(outputStream);
            workbook.close();
            return new ApiResponse("success");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ApiResponse(400, "error");
    }


    @AdminSignIgnore
    @RequestMapping("/agent/query")
    public ApiResponse<ArrayList<String>> getAgentCodeQuery(String merchantCode) {
        List<CeAgentAccountEntity> ceAgentAccountEntities = ceAgentAccountDao.getAccountsMerchantCode(merchantCode);
        ArrayList<String> list = Lists.newArrayList();
        ceAgentAccountEntities.forEach(agentAccountEntity -> {
            list.add(agentAccountEntity.getAgentCode());
        });
        return new ApiResponse<>(list);
    }


    @AdminSignIgnore
    @RequestMapping("/okrupee/login")
    @VisitorAccessible
    public String okRupeeLogin(String agentCode, String code) {
        return okRupeeService.login(agentCode, code);
    }
}
